package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.EmpStoreHouse;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

public class WareHouseDB {
    private static String TAG = "WareHouseDB";
    private static String TABLE_NAME = "WareHouse";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "id  CHAR(30) PRIMARY KEY  NOT NULL,"
                + "qid" + " CHAR(30)," +  "dealer" + " CHAR(30)," + "name" + " CHAR(30)," + "orgList" + " CHAR(500),"+ "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllWareHouse(List<WareHouse> customer) {
        //deleteAll();
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM WareHouse");
        String sql = "insert into WareHouse(qid,id,dealer,name,orgList,modifyTime) values(?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getId() + "");
            stmt.bindString(2, customer.get(i).getId() + "");
            stmt.bindString(3, customer.get(i).getDealer() + "");
            stmt.bindString(4, customer.get(i).getName() + "");
            stmt.bindString(5, customer.get(i).getOrgList() + "");
            stmt.bindString(6, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllWareHouse(List<WareHouse> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllStoreHouse:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            WareHouse firstWarehouse = customer.get(i);
            ContentValues cv = new ContentValues();
            cv.put("id", firstWarehouse.getId() + "");
            cv.put("qid", firstWarehouse.getId() + "");
            cv.put("dealer", firstWarehouse.getDealer() + "");
            cv.put("name", firstWarehouse.getName() + "");
            cv.put("orgList", firstWarehouse.getOrgList() + "");
            cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
            db.insertWithOnConflict("WareHouse", null, cv, SQLiteDatabase.CONFLICT_REPLACE); //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from WareHouse ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM WareHouse");
    }

    public List<WareHouse> findAllWareHouse(String org) {
        List<WareHouse> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from WareHouse", new String[]{});
        Log.d(TAG, "WareHouse:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            WareHouse customer = new WareHouse();
            customer.setId(cursor.getString(0));
            customer.setQid(cursor.getString(1));
            customer.setDealer(cursor.getString(2));
            customer.setName(cursor.getString(3));
            customer.setOrgList(cursor.getString(4));
            if(StringUtil.isEmpty(org)) {
                list.add(customer);
            } else {
                if(hasOrg(cursor.getString(4), org)  && !cursor.getString(3).contains("库位")){
                    Log.d(TAG, "findAllWareHouse:"+cursor.getString(4) + " " + cursor.getString(3));
                    list.add(customer);
                }
            }
        }

        Log.d(TAG, "findAllWareHouse:" + list.size());
        String houseList = "";
        List<WareHouse> tmpList = new ArrayList<>();
        tmpList.clear();
        List<EmpStoreHouse> list1 = new EmpStoreHouseDB().findAllCustomer();
        if(list1.size() == 0){
            tmpList.addAll(list);
        } else {
            if (list1.size() > 0 && list.size() > 0) {
                for (EmpStoreHouse empStoreHouse : list1) {
                    if (empStoreHouse.getEmpId().equals(SharedPreference.getPreferString("id"))) {
                        houseList = empStoreHouse.getStorehouseList();
                    }
                }
                Log.d(TAG, "houseList:" + houseList);
                if (!StringUtil.isEmpty(houseList)) {
                    String[] list2 = houseList.split("_");
                    if (list2.length > 0) {
                        for (String s : list2) {
                            for (WareHouse wareHouse : list) {
                                if (s.equals(wareHouse.getId())) {
                                    Log.d(TAG, "s:" + s);
                                    tmpList.add(wareHouse);

                                }
                            }
                        }
                    }

                } else {
                    tmpList.addAll(list);
                }
                Log.d(TAG, "tmpList:" + list.size());
            }
        }
        cursor.close();
        Log.d(TAG, "findAllEmpWareHouse:" + tmpList.size());
        return tmpList;
    }

    private boolean hasOrg(String string, String org) {
        if(!StringUtil.isEmpty(string) && !StringUtil.isEmpty(org) ){
            if(string.contains(org)){
                return true;
            }
        }
        return false;
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from WareHouse", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasWareHouse true");
            return true;
        } else {
            Log.d(TAG, "hasWareHouse false");
            cursor.close();
            return false;
        }
    }

    public String findWareHouse(String id) {
        Log.d(TAG, "findWareHouse id:" + id);
        String list = "";
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from WareHouse where id =?", new String[]{id});
        if (cursor.moveToFirst()) {
            Log.d(TAG, "findWareHouse moveToFirst" + cursor.getString(3));
            list = cursor.getString(3);
        }
        cursor.close();
        Log.d(TAG, "findWareHouse " + list);
        return list;
    }
}
